﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Serviio.API;

namespace Serviio.WHS
{
    public partial class PresentationOptionsForm : Form
    {
        private static readonly LogFacade log = LogFacade.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public PresentationOptionsForm()
        {
            InitializeComponent();
        }

        public bool Edit(ServiioConnection connection)
        {
            try
            {
                checkboxParentTitle.Checked = connection.Presentation.ShowParentCategoryTitle;

                LoadLanguages(connection);
                comboBoxLanguage.SelectedValue = connection.Presentation.Language;

                LoadCategories(connection);

                if (this.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    connection.Presentation.ShowParentCategoryTitle = checkboxParentTitle.Checked;
                    connection.Presentation.Language = comboBoxLanguage.SelectedValue.ToString();

                    SaveCategories(connection);
                    return connection.Presentation.Update();
                }
                return false;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return false;
            }
        }

        private void LoadLanguages(ServiioConnection connection)
        {
            try
            {
                comboBoxLanguage.DataSource = new BindingSource(connection.Reference.BrowsingCategoriesLanguages, null);
                comboBoxLanguage.DisplayMember = "Value";
                comboBoxLanguage.ValueMember = "Key";
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void LoadCategories(ServiioConnection connection)
        {
            try
            {
                DataGridViewComboBoxColumn col = dataGridViewCategories.Columns[1] as DataGridViewComboBoxColumn;
                col.DisplayMember = "Value";
                col.ValueMember = "Key";
                col.DataSource = ServiioBrowsingCategory.VisibilityChoices;

                PopulateCategories(connection.Presentation.Categories);

                SetReadOnlyRows();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void PopulateCategories(List<ServiioBrowsingCategory> list, string parent="", string prefix = "")
        {
            try
            {
                foreach (ServiioBrowsingCategory category in list)
                {
                    dataGridViewCategories.Rows.Add(prefix + category.Title, category.VisibilityString, category.Id, parent);
                    if (category.SubCategories.Count > 0)
                        PopulateCategories(category.SubCategories, category.Id, prefix + "      ");
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void SaveCategories(ServiioConnection connection)
        {
            try
            {
                for (int i = 0; i < dataGridViewCategories.Rows.Count; i++)
                {
                    DataGridViewRow row = dataGridViewCategories.Rows[i];
                    ServiioBrowsingCategory category = connection.Presentation.FlatCategories[i];
                    category.VisibilityString = row.Cells[1].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void SetReadOnlyRows()
        {
            try
            {
                for (int i = 0; i < dataGridViewCategories.Rows.Count; )
                {
                    DataGridViewRow row = dataGridViewCategories.Rows[i];
                    if ("DISABLED".Equals(row.Cells[1].Value as string))
                    {
                        i = SetChildrenReadOnly(row);
                    }
                    else
                    {
                        i++;
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private int SetChildrenReadOnly(DataGridViewRow parentRow)
        {
            int i;
            for (i = parentRow.Index + 1; i < dataGridViewCategories.Rows.Count;)
            {
                DataGridViewRow childRow = dataGridViewCategories.Rows[i];
                if (childRow.Cells[3].Value.Equals(parentRow.Cells[2].Value))
                {
                    SetRowReadOnly(childRow);
                    i = SetChildrenReadOnly(childRow);
                }
                else
                    return i;
            }
            return i;
        }

        private int SetChildrenNormal(DataGridViewRow parentRow)
        {
            int i;
            for (i = parentRow.Index + 1; i < dataGridViewCategories.Rows.Count;)
            {
                DataGridViewRow childRow = dataGridViewCategories.Rows[i];
                if (childRow.Cells[3].Value.Equals(parentRow.Cells[2].Value))
                {
                    SetRowNormal(childRow);
                    if ("DISABLED".Equals(childRow.Cells[1].Value as string))
                    {
                        i = SetChildrenReadOnly(childRow);
                    }
                    else
                    {
                        i = SetChildrenNormal(childRow);
                    }
                }
                else
                    return i;
            }
            return i;
        }

        private void SetRowReadOnly(DataGridViewRow row)
        {
            try
            {
                row.DefaultCellStyle.ForeColor = Color.FromArgb(201, 205, 217);
                row.DefaultCellStyle.SelectionForeColor = Color.FromArgb(201, 205, 217);
                row.ReadOnly = true;
                DataGridViewComboBoxCell cell = row.Cells[1] as DataGridViewComboBoxCell;
                cell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void SetRowNormal(DataGridViewRow row)
        {
            try
            {
                row.DefaultCellStyle = null;
                row.ReadOnly = false;
                DataGridViewComboBoxCell cell = row.Cells[1] as DataGridViewComboBoxCell;
                cell.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void dataGridViewCategories_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            try
            {
                if (e.Control is ComboBox)
                {
                    ComboBox cbm = e.Control as ComboBox;
                    if (cbm != null)
                    {
                        cbm.SelectedIndexChanged -= cbm_SelectedIndexChanged;
                        cbm.SelectedIndexChanged += cbm_SelectedIndexChanged;
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void cbm_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (!(sender is ComboBox) || String.IsNullOrEmpty(((ComboBox)sender).SelectedValue as String))
                    return;
                DataGridViewRow row = dataGridViewCategories.SelectedRows[0];
                if ("DISABLED".Equals(((ComboBox)sender).SelectedValue))
                    SetChildrenReadOnly(row);
                else
                    SetChildrenNormal(row);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void dataGridViewCategories_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex < 0 || e.RowIndex >= dataGridViewCategories.Rows.Count)
                    return;

                if (e.ColumnIndex != 1)
                    return;

                DataGridViewCell cell = dataGridViewCategories.Rows[e.RowIndex].Cells[1];

                if (cell.ReadOnly)
                    return;

                dataGridViewCategories.CurrentCell = cell;
                //dataGridViewCategories.BeginEdit(true);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void dataGridViewCategories_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                dataGridViewCategories.CurrentCell = null;
                dataGridViewCategories.EndEdit();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

    }
}
